<?php

/**
 * Unique validate
 *
 * @author fusq
 */
class MyValid_Unique extends Zend_Validate_Abstract{
    const QNIQUE = 'unique';
    protected $_messageTemplates = array(self::QNIQUE => "'%value%' has been exist.");
    private $tableName;
    private $field;
    private $id;
    public function isValid ($value)
    {
        $this->_setValue($value);
        $id = $this->checkUnique($value);
        if ($id) {
            $this->_error();
            return false;
        }
        return true;
    }
    public function setId ($id)
    {
        $this->id = $id;
    }
    public function setTableName ($table)
    {
        $this->tableName = $table;
    }
    public function setFieldName ($fie)
    {
        $this->field = $fie;
    }
    public function setFetchAttr($table,$fie,$id=null){
        $this->tableName = $table;
        $this->field = $fie;
        if(isset($id)){
             $this->id = $id;
        }
    }
    public function checkUnique ($value)
    {
        $db_r = Zend_Registry::get("db_r");
        $select = $db_r->select();
        $select->from($this->tableName, 'id');
        $key = $this->field;
        $select->where("lower($key) = ?", strtolower($value));
        if ($this->id) {
            $select->where("id!=?", $this->id);
        }
        $select->where("is_delete=?", '0');
        $sql = $select->__toString();
        return $db_r->fetchOne($sql);
    }
}
